<!--
 * @Author: LiYuan
 * @Date: 2021-02-03 09:19:13
 * @LastEditTime: 2021-02-03 15:24:55
 * @LastEditors: LiYuan
 * @Description: 备件库存 批量出库/入库/调拨/分配
 * @You build it, You run it.
-->
<template>
  <el-dialog :title="title" :visible.sync="visible" :width="width" @close="handleClose">
    <!-- 批量出库 batchOutStock -->
    <part-outstock-batch-form v-if="visible && type === 'batchOutStock'" ref="batchOutStockForm" :sparepart-config="sparepartConfig"></part-outstock-batch-form>

    <!-- 批量入库 batchInStock -->
    <part-instockBatch-form v-if="visible && type === 'batchInStock'" ref="batchInStockForm" :repertory="repertory" :sparepart-config="sparepartConfig"></part-instockBatch-form>

    <!-- 批量调拨 batchTransfer -->
    <part-batch-transfer v-if="visible && type === 'batchTransfer'" ref="batchTransferForm" :repertory="repertory" :sparepart-config="sparepartConfig"></part-batch-transfer>

    <!-- 批量分配 batchSpare -->
    <div class="" slot="title" v-if="visible && type === 'batchSpare'">
      <span class="el-dialog__title"> {{ title }} </span>
      <p class="dialog-title-tip">
        {{ $t('part.tips5') }}
      </p>
    </div>
    <part-spares-batch-form v-if="visible && type === 'batchSpare'" :repertories="repertories" :repertory="repertory" ref="batchSpareForm"></part-spares-batch-form>

    <!-- footer -->
    <div slot="footer" class="dialog-footer">
      <el-button type="ghost" @click="visible = false">{{ $t('common.paas.buttons.cancel') }}</el-button>
      <el-button type="primary" @click="handleConfirm" :disabled="pending">{{ $t('common.base.makeSure') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import _ from 'lodash';
import PartOutStockBatchForm from '../form/PartOutStockBatchForm.vue';
import PartInStockBatchForm from '../form/PartInStockBatchForm.vue';
import PartBatchTransfer from '../form/PartBatchTransfer.vue';
import PartSparesBatchForm from '../form/PartSparesBatchForm.vue';
import { t } from '@src/locales'
export default {
  name: 'stock-batch-opt-dialog',
  components: {
    [PartOutStockBatchForm.name]: PartOutStockBatchForm,
    [PartInStockBatchForm.name]: PartInStockBatchForm,
    [PartSparesBatchForm.name]: PartSparesBatchForm,
    // [PartBatchTransfer.name]: PartBatchTransfer,
    PartBatchTransfer
  },
  props: {
    width: {
      type: String,
      default: "940px"
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    repertories: {
      type: Array,
      default: () => []
    },
    repertory: {
      type: Array,
      default: () => []
    },
    sparepartConfig: {
      type: Object,
      default: () => { }
    },
    type: {
      type: String,
      default: ""
    }
  },
  data: () => {
    return {
      visible: false,
      pending: false,
      typeMap: {
        'batchOutStock': t('part.text1'),
        'batchInStock': t('part.text2'),
        'batchTransfer': t('part.text3'),
        'batchSpare': t('common.base.batchAllot')
      }
    }
  },
  watch: {
    dialogVisible: {
      handler(val) {
        this.visible = val
      },
      immediate: true
    }
  },
  computed: {
    title () {
      return this.type ? this.typeMap[this.type] + t('common.base.operation') : ''
    }
  },
  methods: {
    // 弹窗关闭
    handleClose() {
      this.$emit('close')
    },

    // 确认
    handleConfirm() {
      switch (this.type) {
        case 'batchOutStock':
          this.outstockBatchSave()
          break;
        case 'batchInStock':
          this.instockBatchSave()
          break;
        case 'batchTransfer':
          this.transferBatchSave()
          break;
        case 'batchSpare':
          this.partSparesBatch()
          break;
        default:
          break;
      }
    },

    /**
     * @description: 出库/入库/调拨/分配 form receive 方法
     * @param {String} formType batchOutStock/batchInStock/batchTransfer/batchSpare Form
     * @param {Array} data
     * @param {String} userId
     */
    formReceiveData (formType, data, userId) {
      this.$nextTick(()=> {
        this.$refs[formType].receive(data, userId);
      })
    },

    // 出库（批量）
    outstockBatchSave: _.debounce(async function(){
      let form = this.$refs.batchOutStockForm;

      if(null == form) return;

      let outstock = await form.pack();

      if(!Array.isArray(outstock) || outstock.length == 0) return;

      this.pending = true;

      try {
        let result = await this.$http.post('/partV2/repertory/stockInOutBach', outstock);
        if(result.status == 0){
          this.$platform.toast(t('part.tips6')).then(() => this.$emit('success'));
          this.handleClose()
        } else{
          this.$platform.alert(result.message);
        }
        this.pending = false;
      } catch (error) {
        this.pending = false;
        console.log(error)
      }

    }, 1000),

    // 入库（批量）
    instockBatchSave: _.debounce(async function(){
      let form = this.$refs.batchInStockForm;
      if(null == form) return;

      let instock = await form.pack();
      if(!Array.isArray(instock) || instock.length == 0) return;

      this.pending = true;

      try {
        let result = await this.$http.post('/partV2/repertory/stockInOutBach', instock);

        if (result.status == 0){
          this.$platform.toast(t('part.tips7')).then(() => this.$emit('success'));
          this.handleClose()
        } else{
          this.$platform.alert(result.message);
        }
        this.pending = false;
      } catch (error) {
        this.pending = false;
        console.log(error)
      }

    }, 1000),

    // 批量调拨 (保存)
    transferBatchSave: _.debounce(async function(){
      let form = this.$refs.batchTransferForm;
      if(null == form) return;
      let params = await form.pack();
      if(!Array.isArray(params) || params.length == 0) return;


      if (params.some(s => s.repertoryId === s.targetId)) {

        let message =t('part.tips8', {num:params.map((sr, index) => {
          if (sr.repertoryId === sr.targetId) {
            return index + 1;
          }
          return null
        }).filter(n => n).join('，')});

        if(!await this.$platform.confirm(message)) return;

        params = params.filter(row => row.repertoryId !== row.targetId);
      }

      this.pending = true;

      try {
        let result = await this.$http.post('/partV2/approve/transfer/initiate/batch', params);

        if(result.status == 0){
          this.$platform.toast(t('part.tips9')).then(() => {
            this.$emit('success')
          });
          this.handleClose()
        } else{
          this.$platform.alert(result.message);
        }
        this.pending = false;
      } catch (error) {
        this.pending = false;
        console.log(error)
      }

    }, 1000),

    // 分配 (批量)
    partSparesBatch: _.debounce(async function() {
      let form = this.$refs.batchSpareForm;
      if (!form) return;
      this.pending = true;

      let partSparesData = await form.pack();
      if (!partSparesData) {
        this.pending = false;
        return
      }
      if(partSparesData.length < 1) {
        this.$platform.alert(t('part.tips10'));
        this.pending = false;
        return
      }

      let remark = await form.remarkText();

      try {
        let result = await this.$http.post(`/partV2/approve/allot/initiate/batch?remark=${remark}`, partSparesData);

        if((result && result.status === 0)){

          this.$platform.toast(t('part.tips11')).then(() => {
            this.$emit('success')
            this.handleClose()
          });

        } else{
          this.$platform.alert(result.message);
        }
        this.pending = false;
      } catch (e) {
        console.warn(e);
        this.pending = false;
      }

    }, 1000),
  }
}
</script>

<style></style>
